package com.agriculture.monitor.base;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;


@RestControllerAdvice
public class DefaultExceptionHandler {

    private static Logger LOG = LoggerFactory.getLogger(DefaultExceptionHandler.class);

    /**
     * 捕获参数异常
     *
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResultInfo handleValidException(MethodArgumentNotValidException e) {
        for (ObjectError objectError : e.getBindingResult().getAllErrors()) {
            LOG.error(" 错误参数：：{}", objectError.getDefaultMessage());
        }
        return new ResultInfo(ResultInfo.FAILURE,  e.getBindingResult().getFieldError().getDefaultMessage());
    }

    /**
     * 捕捉异常
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(value = BaseException.class)
    @ResponseBody
    public ResultInfo handleException(BaseException ex) {
        LOG.error("》》》 BaseException ：{}", ex.getMessage());
        return new ResultInfo(ex.getCode(), ex.getMessage());
    }

    /**
     * 捕捉异常
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResultInfo handleException(Exception ex) {
        LOG.error("### 发生异常 ### {},{}", ex.getMessage(),ex);
        return new ResultInfo(ResultInfo.FAILURE, "系统异常",ex.getMessage());
    }


}
